package com.sunrise.gateway.web.core;

import com.alibaba.fastjson.JSONObject;
import com.dap.exception.BusinessException;
import com.dap.exception.PlatformException;
import com.dap.param.StringInput;
import com.sunrise.gateway.commons.CommonUtils;
import com.dap.utils.ExcelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Enumeration;

/***
 * @author wangmin
 */
public abstract class ExportEngineBase extends EngineBase {
    private final static Logger LOGGER = LoggerFactory.getLogger(ExportEngineBase.class);

    protected abstract String getModelFilePath();

    public void execute(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String group = CommonUtils.getGroup(req);

        // 获取参数 - 起始行, 从0开始
        int startRow = 1;
        String startRowStr = req.getParameter("startRow");
        if (!StringUtils.isEmpty(startRowStr)) {
            try {
                startRow = Integer.parseInt(startRowStr);
            } catch (Exception e) {
            }
        }

        // 获取参数 - 起始列, 从0开始
        int startCol = 0;
        String startColStr = req.getParameter("startCol");
        if (!StringUtils.isEmpty(startColStr)) {
            try {
                startCol = Integer.parseInt(startColStr);
            } catch (Exception e) {
            }
        }

        // 获取参数 - 模板名称
        String modelName = req.getParameter("modelName");
        if (StringUtils.isEmpty(modelName)) {
            throw new PlatformException("获取模板名失败");
        }

        StringInput input = new StringInput();

        JSONObject json = new JSONObject();
        Enumeration pn = req.getParameterNames();
        while (pn.hasMoreElements()) {
            String parameterName = (String) pn.nextElement();
            String value = req.getParameter(parameterName);
            json.put(parameterName, value);
        }

        input.setBody(json.toJSONString());

        // ctrlData添加基本信息
        fillSessionInfoIntoCtrlDataInterface.fill(input, group, req);

        Object excelData = executeRequestObject(group, input, false);
        if (null == excelData) {
            throw new BusinessException(com.dap.commons.Constants.ResponseCode.EXCEL_NO_DATA);
        }

        try {
            String fileName = req.getParameter("fileName");
            if (org.apache.commons.lang.StringUtils.isEmpty(fileName)) {
                fileName = "default-name.xls";
            }

            String userAgent = req.getHeader("User-Agent");
            String dispositionFileName = CommonUtils.generateDispositionFileName(fileName, userAgent);
            resp.setHeader("Content-disposition", "attachment; " + dispositionFileName);
            resp.setContentType("application/vnd.ms-excel;charset=UTF-8");
        } catch (Exception e) {
            LOGGER.warn("", e);
            throw new PlatformException("返回结果异常");
        }

        String modelFileWholePath = resolveModelFileWholePath(modelName);
        try {
            ExcelUtils.writeExcel(modelFileWholePath, excelData, startRow, startCol, resp.getOutputStream());
        } catch (Exception e) {
            LOGGER.info("", e);
        }
    }

    private String resolveModelFileWholePath(String modelName) {
        String path = getModelFilePath() + "/" + modelName + ".xls";
        if ((new File(path)).exists()) {
            return path;
        } else {
            return path + "x";
        }
    }
}
